<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Layout,
  Menu,
  message,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from 'ant-design-vue';

const { Title } = Typography;
const { Sider, Content } = Layout;
const router = useRouter();

// 当前选中的菜单项
const selectedMenuKey = ref('today-departure');
// 展开的菜单项 - 使用 openKeys 来控制展开状态
const openKeys = ref([
  'today-todo',
  'order-status',
  'group-booking',
  'external-orders',
  'business-records',
]);

// 菜单项配置
const menuItems = [
  {
    key: 'today-todo',
    label: '今日待办',
    icon: 'ant-design:calendar-outlined',
    children: [
      { key: 'today-arrival', label: '今日预抵' },
      { key: 'today-departure', label: '今日预离' },
      { key: 'today-checkin', label: '今日入住' },
      { key: 'today-departed', label: '今日已离' },
      { key: 'should-depart', label: '应离未离' },
    ],
  },
  {
    key: 'order-status',
    label: '订单状态',
    icon: 'ant-design:file-text-outlined',
    children: [
      { key: 'in-reservation', label: '预订中' },
      { key: 'in-stay', label: '在住中' },
      { key: 'checked-out', label: '已退房' },
      { key: 'on-account', label: '已挂账' },
      { key: 'noshow', label: 'NOSHOW' },
      { key: 'all-reservations', label: '全部预订' },
      { key: 'all-registrations', label: '全部登记' },
      { key: 'cancelled', label: '已取消' },
    ],
  },
  {
    key: 'group-booking',
    label: '联房团队',
    icon: 'ant-design:team-outlined',
    children: [
      { key: 'group-reservation', label: '团队预订' },
      { key: 'group-in-stay', label: '团队在住' },
    ],
  },
  {
    key: 'external-orders',
    label: '外部订单',
    icon: 'ant-design:global-outlined',
    children: [
      { key: 'ctrip-orders', label: '携程订单' },
      { key: 'meituan-orders', label: '美团订单' },
      { key: 'in-stay-deposit', label: '在住押金' },
    ],
  },
  {
    key: 'business-records',
    label: '业务记录',
    icon: 'ant-design:history-outlined',
    children: [
      { key: 'card-making', label: '制卡记录' },
      { key: 'security-upload', label: '公安上传记录' },
    ],
  },
];

// 订单数据
const orders = ref([
  {
    id: '1',
    roomNumber: 'c122s',
    roomType: 'C122S型',
    guestSource: '美团',
    guestName: '21',
    contactPhone: '13579246810',
    payment: 140,
    consumption: 6300,
    preAuth: 0,
    checkInTime: '07-09 14:39',
    checkOutTime: '08-17 00:07',
    status: '未结',
    remarks: '',
    orderNumber: 'ORD001',
  },
  {
    id: '2',
    roomNumber: 'b56s',
    roomType: '标准双床房',
    guestSource: '美团',
    guestName: '阿萨德 李文龙',
    contactPhone: '18521009400',
    payment: 0.02,
    consumption: 0.17,
    preAuth: 0,
    checkInTime: '07-31 15:20',
    checkOutTime: '08-17 00:07',
    status: '未结',
    remarks: '',
    orderNumber: 'ORD002',
  },
  {
    id: '3',
    roomNumber: 'b71s',
    roomType: '标准双床房',
    guestSource: '散客',
    guestName: '张三',
    contactPhone: '13800138000',
    payment: 100,
    consumption: 1450.01,
    preAuth: 0,
    checkInTime: '08-04 10:32',
    checkOutTime: '08-17 00:07',
    status: '未结',
    remarks: '',
    orderNumber: 'ORD003',
  },
  {
    id: '4',
    roomNumber: 'b84s',
    roomType: '标准双床房',
    guestSource: '散客',
    guestName: '李四',
    contactPhone: '13900139000',
    payment: 10,
    consumption: 10,
    preAuth: 0,
    checkInTime: '08-15 15:14',
    checkOutTime: '08-17 15:01',
    status: '未结',
    remarks: '',
    orderNumber: 'ORD004',
  },
  {
    id: '5',
    roomNumber: 'a101',
    roomType: '豪华大床房',
    guestSource: '携程',
    guestName: '王五',
    contactPhone: '13700137000',
    payment: 200,
    consumption: 800,
    preAuth: 500,
    checkInTime: '08-16 12:00',
    checkOutTime: '08-17 12:00',
    status: '已结',
    remarks: 'VIP客户',
    orderNumber: 'ORD005',
  },
]);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  guestSource: '',
  status: '',
  dateRange: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条数据`,
});

// 获取客源颜色
const getGuestSourceColor = (source: string) => {
  const colors = {
    美团: 'green',
    携程: 'blue',
    散客: 'orange',
    团队: 'purple',
  };
  return colors[source] || 'default';
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colors = {
    未结: 'red',
    已结: 'green',
    已挂账: 'orange',
    已取消: 'gray',
  };
  return colors[status] || 'default';
};

// 表格列定义
const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    key: 'id',
    width: 60,
  },
  {
    title: '房号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '房型名称',
    dataIndex: 'roomType',
    key: 'roomType',
    width: 120,
  },
  {
    title: '客源',
    dataIndex: 'guestSource',
    key: 'guestSource',
    width: 100,
  },
  {
    title: '宾客姓名',
    dataIndex: 'guestName',
    key: 'guestName',
    width: 120,
  },
  {
    title: '联系电话',
    dataIndex: 'contactPhone',
    key: 'contactPhone',
    width: 120,
  },
  {
    title: '支付',
    dataIndex: 'payment',
    key: 'payment',
    width: 100,
  },
  {
    title: '消费',
    dataIndex: 'consumption',
    key: 'consumption',
    width: 100,
  },
  {
    title: '预授权',
    dataIndex: 'preAuth',
    key: 'preAuth',
    width: 100,
  },
  {
    title: '入住时间',
    dataIndex: 'checkInTime',
    key: 'checkInTime',
    width: 120,
  },
  {
    title: '离店时间',
    dataIndex: 'checkOutTime',
    key: 'checkOutTime',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '备注信息',
    dataIndex: 'remarks',
    key: 'remarks',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
];

// 过滤后的数据
const filteredOrders = computed(() => {
  let result = orders.value;

  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase();
    result = result.filter(
      (order) =>
        order.guestName.toLowerCase().includes(keyword) ||
        order.contactPhone.includes(keyword) ||
        order.orderNumber.toLowerCase().includes(keyword) ||
        order.roomNumber.toLowerCase().includes(keyword),
    );
  }

  if (searchForm.guestSource) {
    result = result.filter(
      (order) => order.guestSource === searchForm.guestSource,
    );
  }

  if (searchForm.status) {
    result = result.filter((order) => order.status === searchForm.status);
  }

  return result;
});

// 订单统计
const orderStatistics = computed(() => {
  const total = orders.value.length;
  const unsettled = orders.value.filter((o) => o.status === '未结').length;
  const settled = orders.value.filter((o) => o.status === '已结').length;
  const onAccount = orders.value.filter((o) => o.status === '已挂账').length;
  const cancelled = orders.value.filter((o) => o.status === '已取消').length;

  // 按客源统计
  const sourceStats = orders.value.reduce(
    (acc, order) => {
      acc[order.guestSource] = (acc[order.guestSource] || 0) + 1;
      return acc;
    },
    {} as Record<string, number>,
  );

  // 总收入和消费
  const totalPayment = orders.value.reduce(
    (sum, order) => sum + order.payment,
    0,
  );
  const totalConsumption = orders.value.reduce(
    (sum, order) => sum + order.consumption,
    0,
  );

  return {
    total,
    unsettled,
    settled,
    onAccount,
    cancelled,
    sourceStats,
    totalPayment,
    totalConsumption,
  };
});

// 获取当前页面标题
const currentPageTitle = computed(() => {
  const findMenuItem = (items: any[], key: string): any => {
    for (const item of items) {
      if (item.key === key) return item;
      if (item.children) {
        const found = findMenuItem(item.children, key);
        if (found) return found;
      }
    }
    return null;
  };

  const menuItem = findMenuItem(menuItems, selectedMenuKey.value);
  return menuItem ? menuItem.label : '订单管理';
});

// 菜单展开/收缩处理
const handleOpenChange = (keys: string[]) => {
  openKeys.value = keys;
};

// 菜单点击处理
const handleMenuClick = ({ key }: { key: string }) => {
  selectedMenuKey.value = key;

  // 根据菜单项跳转到对应页面
  if (key === 'card-making') {
    router.push('/hotel/order-management/card-making');
  } else if (key === 'security-upload') {
    router.push('/hotel/order-management/security-upload');
  } else {
    // 这里可以根据不同的菜单项加载不同的数据
    message.info(`切换到: ${currentPageTitle.value}`);
  }
};

// 返回主页面
const backToMain = () => {
  router.push('/hotel/order-management');
};

// 查看订单详情
const viewOrder = (record: any) => {
  router.push(`/hotel/order-management/detail/${record.id}`);
};

// 办理入住
const checkIn = (record: any) => {
  message.success(`订单 ${record.orderNumber} 入住办理成功`);
};

// 续住
const extendStay = (record: any) => {
  message.success(`订单 ${record.orderNumber} 续住办理成功`);
};

// 退房
const checkOut = (record: any) => {
  message.success(`订单 ${record.orderNumber} 退房办理成功`);
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    guestSource: '',
    status: '',
    dateRange: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

// 导出数据
const exportData = () => {
  message.success('数据导出成功');
};

// 读身份证
const readIdCard = () => {
  message.info('身份证读取功能开发中...');
};

onMounted(() => {
  pagination.total = filteredOrders.value.length;
});
</script>

<template>
  <Layout class="order-management-layout">
    <!-- 左侧导航菜单 -->
    <Sider width="280" class="order-sider">
      <Menu
        mode="inline"
        :selected-keys="[selectedMenuKey]"
        :open-keys="openKeys"
        class="order-menu"
        @click="handleMenuClick"
        @open-change="handleOpenChange"
      >
        <Menu.SubMenu
          v-for="item in menuItems"
          :key="item.key"
          :title="item.label"
        >
          <template #icon>
            <IconifyIcon :icon="item.icon" />
          </template>
          <Menu.Item
            v-for="child in item.children"
            :key="child.key"
            :class="{ 'menu-item-active': selectedMenuKey === child.key }"
          >
            {{ child.label }}
          </Menu.Item>
        </Menu.SubMenu>
      </Menu>
    </Sider>

    <!-- 主内容区域 -->
    <Content class="order-content">
      <div class="order-management">
        <!-- 页面标题 -->
        <div class="page-header">
          <Title level="2">{{ currentPageTitle }}</Title>
          <Space>
            <Button type="primary" @click="exportData">
              <IconifyIcon icon="ant-design:download-outlined" />
              导出
            </Button>
          </Space>
        </div>

        <!-- 统计信息 -->
        <Row :gutter="16" class="statistics-row">
          <Col :span="4">
            <Card class="stat-card">
              <div class="stat-content">
                <div class="stat-number total">{{ orderStatistics.total }}</div>
                <div class="stat-label">订单总数</div>
              </div>
            </Card>
          </Col>
          <Col :span="4">
            <Card class="stat-card">
              <div class="stat-content">
                <div class="stat-number unsettled">
                  {{ orderStatistics.unsettled }}
                </div>
                <div class="stat-label">未结订单</div>
              </div>
            </Card>
          </Col>
          <Col :span="4">
            <Card class="stat-card">
              <div class="stat-content">
                <div class="stat-number settled">
                  {{ orderStatistics.settled }}
                </div>
                <div class="stat-label">已结订单</div>
              </div>
            </Card>
          </Col>
          <Col :span="4">
            <Card class="stat-card">
              <div class="stat-content">
                <div class="stat-number onAccount">
                  {{ orderStatistics.onAccount }}
                </div>
                <div class="stat-label">已挂账</div>
              </div>
            </Card>
          </Col>
          <Col :span="4">
            <Card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">
                  ¥{{ orderStatistics.totalPayment.toFixed(2) }}
                </div>
                <div class="stat-label">总收入</div>
              </div>
            </Card>
          </Col>
          <Col :span="4">
            <Card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">
                  ¥{{ orderStatistics.totalConsumption.toFixed(2) }}
                </div>
                <div class="stat-label">总消费</div>
              </div>
            </Card>
          </Col>
        </Row>

        <!-- 搜索表单 -->
        <Card class="search-card">
          <Form layout="inline" :model="searchForm" class="search-form">
            <Form.Item label="姓名">
              <Input
                v-model="searchForm.keyword"
                placeholder="请输入姓名"
                allow-clear
                style="width: 150px"
              />
            </Form.Item>
            <Form.Item label="搜索">
              <Input
                v-model="searchForm.keyword"
                placeholder="手机号、中文首字母、预订单号"
                allow-clear
                style="width: 300px"
              />
            </Form.Item>
            <Form.Item label="客源">
              <Select
                v-model="searchForm.guestSource"
                placeholder="请选择客源"
                allow-clear
                style="width: 120px"
              >
                <Select.Option value="美团">美团</Select.Option>
                <Select.Option value="携程">携程</Select.Option>
                <Select.Option value="散客">散客</Select.Option>
                <Select.Option value="团队">团队</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="状态">
              <Select
                v-model="searchForm.status"
                placeholder="请选择状态"
                allow-clear
                style="width: 120px"
              >
                <Select.Option value="未结">未结</Select.Option>
                <Select.Option value="已结">已结</Select.Option>
                <Select.Option value="已挂账">已挂账</Select.Option>
                <Select.Option value="已取消">已取消</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" @click="handleSearch">
                  <IconifyIcon icon="ant-design:search-outlined" />
                  查询
                </Button>
                <Button @click="handleReset">
                  <IconifyIcon icon="ant-design:reload-outlined" />
                  重置
                </Button>
                <Button @click="readIdCard">
                  <IconifyIcon icon="ant-design:idcard-outlined" />
                  读身份证
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        <!-- 订单列表 -->
        <Card :title="currentPageTitle" class="list-card">
          <Table
            :columns="columns"
            :data-source="filteredOrders"
            :pagination="pagination"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'guestSource'">
                <Tag :color="getGuestSourceColor(record.guestSource)">
                  {{ record.guestSource }}
                </Tag>
              </template>
              <template v-else-if="column.key === 'payment'">
                ¥{{ record.payment.toFixed(2) }}
              </template>
              <template v-else-if="column.key === 'consumption'">
                ¥{{ record.consumption.toFixed(2) }}
              </template>
              <template v-else-if="column.key === 'preAuth'">
                ¥{{ record.preAuth.toFixed(2) }}
              </template>
              <template v-else-if="column.key === 'status'">
                <Tag :color="getStatusColor(record.status)">
                  {{ record.status }}
                </Tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <Space>
                  <Button type="link" size="small" @click="viewOrder(record)">
                    详情
                  </Button>
                  <Button type="link" size="small" @click="checkIn(record)">
                    入账
                  </Button>
                  <Button type="link" size="small" @click="extendStay(record)">
                    续住
                  </Button>
                  <Button type="link" size="small" @click="checkOut(record)">
                    退房
                  </Button>
                </Space>
              </template>
            </template>
          </Table>
        </Card>
      </div>
    </Content>
  </Layout>
</template>

<style scoped>
.order-management-layout {
  height: 100vh;
}

.order-sider {
  background: #fff;
  border-right: 1px solid #f0f0f0;
}

.sider-header {
  padding: 16px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.order-menu {
  border-right: none;
}

.menu-item-active {
  color: #1890ff !important;
  background-color: #e6f7ff !important;
}

.order-content {
  overflow-y: auto;
  background: #f5f5f5;
}

.order-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.statistics-row {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 16px;
}

.stat-number {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: bold;
}

.stat-number.total {
  color: #1890ff;
}

.stat-number.unsettled {
  color: #f5222d;
}

.stat-number.settled {
  color: #52c41a;
}

.stat-number.onAccount {
  color: #faad14;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.search-card {
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.list-card {
  background: white;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}

:deep(.ant-menu-submenu-title) {
  font-weight: 500;
}

:deep(.ant-menu-item) {
  padding-left: 48px !important;
  margin: 0;
}

:deep(.ant-menu-submenu) {
  margin-bottom: 8px;
}
</style>
